const { JJWithDrawApply, JJUserAccount, Ctcdb, JJUserAccountBill, JJUser } = require('../../models/ctcdb');
const BaseResp = require('../../utils/baseResp');
const errorCode = require('../../utils/errorCode');
const moment = require('moment');

async function createApply({ userId, amount }) {
  const user = await JJUser.findOne({
    where: {
      id: userId
    },
    raw: true,
    attributes: ['identity', 'id', 'isForbidden']
  });
  if (!user) {
    throw BaseResp.error(errorCode.USER.NOT_FOUND)
  }
  if (user.isForbidden) {
    throw BaseResp.error(errorCode.USER.HAS_END_SIGN)
  }
  const startDay = moment().startOf('d');
  const endDay = moment().endOf('d');
  const applyInfo = await JJWithDrawApply.findOne({
    where: {
      createTime: {
        $lte: new Date(endDay),
        $gte: new Date(startDay)
      }
    },
    attributes: ['id'],
    raw: true
  });
  if (applyInfo) {
    throw BaseResp.error(errorCode.wxchat.WITH_DRAW_ONLY_ONE)
  }
  const account = await JJUserAccount.findOne({
    where: {
      jUserId: userId
    },
    attributes: ['balance', 'balanceCash', 'id', 'status'],
    raw: true
  });
  if (!account) {
    throw BaseResp.error(errorCode.USER.ACCOUNT_ERROR)
  }
  // todo 这里注意下，现在用的balance余额，并不是实际金额,是否要创建账单
  const { balance } = account;
  if (amount > balance) {
    throw BaseResp.error(errorCode.USER.ACCOUNT_NOT_ENOUGH)
  }
  let sql = `update jj_user_account set balance = balance-${amount},lock_sum = lock_sum+${amount} where ref_jj_user_id = ${userId}`;
  const transaction = await Ctcdb.transaction();
  try {
    // 创建申请单
    await JJWithDrawApply.create({
      status: 0,
      amount,
      applyUserId: userId
    }, {
      transaction
    });
    // 创建提现申请
    await Ctcdb.query(sql, { transaction });
    await JJUserAccountBill.create({
      amount: -amount,
      type: 'WIDTH_DRAW',
      remark: `提现`,
      userId: userId
    }, {
      transaction
    });
    // 事务提交
    await transaction.commit();
  } catch(e) {
    if (transaction) {
      await transaction.rollback()
    }
    return Promise.reject(e)
  }
}

module.exports = {
  createApply
};
